package pe.edu.upc.e41a.javasoft.jsf;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.faces.application.Application;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.html.HtmlOutputText;
import javax.faces.component.html.HtmlPanelGrid;
import javax.faces.context.FacesContext;
import javax.faces.convert.DateTimeConverter;
import org.primefaces.component.autocomplete.AutoComplete;
import org.primefaces.component.calendar.Calendar;
import org.primefaces.component.message.Message;
import org.primefaces.context.RequestContext;
import org.primefaces.event.CloseEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.roo.addon.jsf.managedbean.RooJsfManagedBean;
import org.springframework.roo.addon.serializable.RooSerializable;
import pe.edu.upc.e41a.javasoft.domain.Publicacion;
import pe.edu.upc.e41a.javasoft.domain.Visita;
import pe.edu.upc.e41a.javasoft.jsf.converter.PublicacionConverter;
import pe.edu.upc.e41a.javasoft.service.PublicacionService;
import pe.edu.upc.e41a.javasoft.service.VisitaService;

@ManagedBean(name = "visitaBean")
@SessionScoped
@Configurable
@RooSerializable
@RooJsfManagedBean(entity = Visita.class, beanName = "visitaBean")
public class VisitaBean implements Serializable {

	private static final long serialVersionUID = 1L;

	@Autowired
    VisitaService visitaService;

	@Autowired
    PublicacionService publicacionService;

	private String name = "Visitas";

	private Visita visita;

	private List<Visita> allVisitas;

	private boolean dataVisible = false;

	private List<String> columns;

	private HtmlPanelGrid createPanelGrid;

	private HtmlPanelGrid editPanelGrid;

	private HtmlPanelGrid viewPanelGrid;

	private boolean createDialogVisible = false;

	@PostConstruct
    public void init() {
        columns = new ArrayList<String>();
        columns.add("fechaRegistro");
    }

	public String getName() {
        return name;
    }

	public List<String> getColumns() {
        return columns;
    }

	public List<Visita> getAllVisitas() {
        return allVisitas;
    }

	public void setAllVisitas(List<Visita> allVisitas) {
        this.allVisitas = allVisitas;
    }

	public String findAllVisitas() {
        allVisitas = visitaService.findAllVisitas();
        dataVisible = !allVisitas.isEmpty();
        return null;
    }

	public boolean isDataVisible() {
        return dataVisible;
    }

	public void setDataVisible(boolean dataVisible) {
        this.dataVisible = dataVisible;
    }

	public HtmlPanelGrid getCreatePanelGrid() {
        if (createPanelGrid == null) {
            createPanelGrid = populateCreatePanel();
        }
        return createPanelGrid;
    }

	public void setCreatePanelGrid(HtmlPanelGrid createPanelGrid) {
        this.createPanelGrid = createPanelGrid;
    }

	public HtmlPanelGrid getEditPanelGrid() {
        if (editPanelGrid == null) {
            editPanelGrid = populateEditPanel();
        }
        return editPanelGrid;
    }

	public void setEditPanelGrid(HtmlPanelGrid editPanelGrid) {
        this.editPanelGrid = editPanelGrid;
    }

	public HtmlPanelGrid getViewPanelGrid() {
        if (viewPanelGrid == null) {
            viewPanelGrid = populateViewPanel();
        }
        return viewPanelGrid;
    }

	public void setViewPanelGrid(HtmlPanelGrid viewPanelGrid) {
        this.viewPanelGrid = viewPanelGrid;
    }

	public HtmlPanelGrid populateCreatePanel() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        Application application = facesContext.getApplication();
        ExpressionFactory expressionFactory = application.getExpressionFactory();
        ELContext elContext = facesContext.getELContext();
        
        HtmlPanelGrid htmlPanelGrid = (HtmlPanelGrid) application.createComponent(HtmlPanelGrid.COMPONENT_TYPE);
        
        HtmlOutputText publicacionCreateOutput = (HtmlOutputText) application.createComponent(HtmlOutputText.COMPONENT_TYPE);
        publicacionCreateOutput.setId("publicacionCreateOutput");
        publicacionCreateOutput.setValue("Publicacion:   ");
        htmlPanelGrid.getChildren().add(publicacionCreateOutput);
        
        AutoComplete publicacionCreateInput = (AutoComplete) application.createComponent(AutoComplete.COMPONENT_TYPE);
        publicacionCreateInput.setId("publicacionCreateInput");
        publicacionCreateInput.setValueExpression("value", expressionFactory.createValueExpression(elContext, "#{visitaBean.visita.publicacion}", Publicacion.class));
        publicacionCreateInput.setCompleteMethod(expressionFactory.createMethodExpression(elContext, "#{visitaBean.completePublicacion}", List.class, new Class[] { String.class }));
        publicacionCreateInput.setDropdown(true);
        publicacionCreateInput.setValueExpression("var", expressionFactory.createValueExpression(elContext, "publicacion", String.class));
        publicacionCreateInput.setValueExpression("itemLabel", expressionFactory.createValueExpression(elContext, "#{publicacion.titulo} #{publicacion.descripcion} #{publicacion.tipo} #{publicacion.cantidad}", String.class));
        publicacionCreateInput.setValueExpression("itemValue", expressionFactory.createValueExpression(elContext, "#{publicacion}", Publicacion.class));
        publicacionCreateInput.setConverter(new PublicacionConverter());
        publicacionCreateInput.setRequired(false);
        htmlPanelGrid.getChildren().add(publicacionCreateInput);
        
        Message publicacionCreateInputMessage = (Message) application.createComponent(Message.COMPONENT_TYPE);
        publicacionCreateInputMessage.setId("publicacionCreateInputMessage");
        publicacionCreateInputMessage.setFor("publicacionCreateInput");
        publicacionCreateInputMessage.setDisplay("icon");
        htmlPanelGrid.getChildren().add(publicacionCreateInputMessage);
        
        HtmlOutputText fechaRegistroCreateOutput = (HtmlOutputText) application.createComponent(HtmlOutputText.COMPONENT_TYPE);
        fechaRegistroCreateOutput.setId("fechaRegistroCreateOutput");
        fechaRegistroCreateOutput.setValue("Fecha Registro: * ");
        htmlPanelGrid.getChildren().add(fechaRegistroCreateOutput);
        
        Calendar fechaRegistroCreateInput = (Calendar) application.createComponent(Calendar.COMPONENT_TYPE);
        fechaRegistroCreateInput.setId("fechaRegistroCreateInput");
        fechaRegistroCreateInput.setValueExpression("value", expressionFactory.createValueExpression(elContext, "#{visitaBean.visita.fechaRegistro}", Date.class));
        fechaRegistroCreateInput.setNavigator(true);
        fechaRegistroCreateInput.setEffect("slideDown");
        fechaRegistroCreateInput.setPattern("dd/MM/yyyy");
        fechaRegistroCreateInput.setRequired(true);
        htmlPanelGrid.getChildren().add(fechaRegistroCreateInput);
        
        Message fechaRegistroCreateInputMessage = (Message) application.createComponent(Message.COMPONENT_TYPE);
        fechaRegistroCreateInputMessage.setId("fechaRegistroCreateInputMessage");
        fechaRegistroCreateInputMessage.setFor("fechaRegistroCreateInput");
        fechaRegistroCreateInputMessage.setDisplay("icon");
        htmlPanelGrid.getChildren().add(fechaRegistroCreateInputMessage);
        
        return htmlPanelGrid;
    }

	public HtmlPanelGrid populateEditPanel() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        Application application = facesContext.getApplication();
        ExpressionFactory expressionFactory = application.getExpressionFactory();
        ELContext elContext = facesContext.getELContext();
        
        HtmlPanelGrid htmlPanelGrid = (HtmlPanelGrid) application.createComponent(HtmlPanelGrid.COMPONENT_TYPE);
        
        HtmlOutputText publicacionEditOutput = (HtmlOutputText) application.createComponent(HtmlOutputText.COMPONENT_TYPE);
        publicacionEditOutput.setId("publicacionEditOutput");
        publicacionEditOutput.setValue("Publicacion:   ");
        htmlPanelGrid.getChildren().add(publicacionEditOutput);
        
        AutoComplete publicacionEditInput = (AutoComplete) application.createComponent(AutoComplete.COMPONENT_TYPE);
        publicacionEditInput.setId("publicacionEditInput");
        publicacionEditInput.setValueExpression("value", expressionFactory.createValueExpression(elContext, "#{visitaBean.visita.publicacion}", Publicacion.class));
        publicacionEditInput.setCompleteMethod(expressionFactory.createMethodExpression(elContext, "#{visitaBean.completePublicacion}", List.class, new Class[] { String.class }));
        publicacionEditInput.setDropdown(true);
        publicacionEditInput.setValueExpression("var", expressionFactory.createValueExpression(elContext, "publicacion", String.class));
        publicacionEditInput.setValueExpression("itemLabel", expressionFactory.createValueExpression(elContext, "#{publicacion.titulo} #{publicacion.descripcion} #{publicacion.tipo} #{publicacion.cantidad}", String.class));
        publicacionEditInput.setValueExpression("itemValue", expressionFactory.createValueExpression(elContext, "#{publicacion}", Publicacion.class));
        publicacionEditInput.setConverter(new PublicacionConverter());
        publicacionEditInput.setRequired(false);
        htmlPanelGrid.getChildren().add(publicacionEditInput);
        
        Message publicacionEditInputMessage = (Message) application.createComponent(Message.COMPONENT_TYPE);
        publicacionEditInputMessage.setId("publicacionEditInputMessage");
        publicacionEditInputMessage.setFor("publicacionEditInput");
        publicacionEditInputMessage.setDisplay("icon");
        htmlPanelGrid.getChildren().add(publicacionEditInputMessage);
        
        HtmlOutputText fechaRegistroEditOutput = (HtmlOutputText) application.createComponent(HtmlOutputText.COMPONENT_TYPE);
        fechaRegistroEditOutput.setId("fechaRegistroEditOutput");
        fechaRegistroEditOutput.setValue("Fecha Registro: * ");
        htmlPanelGrid.getChildren().add(fechaRegistroEditOutput);
        
        Calendar fechaRegistroEditInput = (Calendar) application.createComponent(Calendar.COMPONENT_TYPE);
        fechaRegistroEditInput.setId("fechaRegistroEditInput");
        fechaRegistroEditInput.setValueExpression("value", expressionFactory.createValueExpression(elContext, "#{visitaBean.visita.fechaRegistro}", Date.class));
        fechaRegistroEditInput.setNavigator(true);
        fechaRegistroEditInput.setEffect("slideDown");
        fechaRegistroEditInput.setPattern("dd/MM/yyyy");
        fechaRegistroEditInput.setRequired(true);
        htmlPanelGrid.getChildren().add(fechaRegistroEditInput);
        
        Message fechaRegistroEditInputMessage = (Message) application.createComponent(Message.COMPONENT_TYPE);
        fechaRegistroEditInputMessage.setId("fechaRegistroEditInputMessage");
        fechaRegistroEditInputMessage.setFor("fechaRegistroEditInput");
        fechaRegistroEditInputMessage.setDisplay("icon");
        htmlPanelGrid.getChildren().add(fechaRegistroEditInputMessage);
        
        return htmlPanelGrid;
    }

	public HtmlPanelGrid populateViewPanel() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        Application application = facesContext.getApplication();
        ExpressionFactory expressionFactory = application.getExpressionFactory();
        ELContext elContext = facesContext.getELContext();
        
        HtmlPanelGrid htmlPanelGrid = (HtmlPanelGrid) application.createComponent(HtmlPanelGrid.COMPONENT_TYPE);
        
        HtmlOutputText publicacionLabel = (HtmlOutputText) application.createComponent(HtmlOutputText.COMPONENT_TYPE);
        publicacionLabel.setId("publicacionLabel");
        publicacionLabel.setValue("Publicacion:   ");
        htmlPanelGrid.getChildren().add(publicacionLabel);
        
        HtmlOutputText publicacionValue = (HtmlOutputText) application.createComponent(HtmlOutputText.COMPONENT_TYPE);
        publicacionValue.setValueExpression("value", expressionFactory.createValueExpression(elContext, "#{visitaBean.visita.publicacion}", Publicacion.class));
        publicacionValue.setConverter(new PublicacionConverter());
        htmlPanelGrid.getChildren().add(publicacionValue);
        
        HtmlOutputText fechaRegistroLabel = (HtmlOutputText) application.createComponent(HtmlOutputText.COMPONENT_TYPE);
        fechaRegistroLabel.setId("fechaRegistroLabel");
        fechaRegistroLabel.setValue("Fecha Registro:   ");
        htmlPanelGrid.getChildren().add(fechaRegistroLabel);
        
        HtmlOutputText fechaRegistroValue = (HtmlOutputText) application.createComponent(HtmlOutputText.COMPONENT_TYPE);
        fechaRegistroValue.setValueExpression("value", expressionFactory.createValueExpression(elContext, "#{visitaBean.visita.fechaRegistro}", Date.class));
        DateTimeConverter fechaRegistroValueConverter = (DateTimeConverter) application.createConverter(DateTimeConverter.CONVERTER_ID);
        fechaRegistroValueConverter.setPattern("dd/MM/yyyy");
        fechaRegistroValue.setConverter(fechaRegistroValueConverter);
        htmlPanelGrid.getChildren().add(fechaRegistroValue);
        
        return htmlPanelGrid;
    }

	public Visita getVisita() {
        if (visita == null) {
            visita = new Visita();
        }
        return visita;
    }

	public void setVisita(Visita visita) {
        this.visita = visita;
    }

	public List<Publicacion> completePublicacion(String query) {
        List<Publicacion> suggestions = new ArrayList<Publicacion>();
        for (Publicacion publicacion : publicacionService.findAllPublicacions()) {
            String publicacionStr = String.valueOf(publicacion.getTitulo() +  " "  + publicacion.getDescripcion() +  " "  + publicacion.getTipo() +  " "  + publicacion.getCantidad());
            if (publicacionStr.toLowerCase().startsWith(query.toLowerCase())) {
                suggestions.add(publicacion);
            }
        }
        return suggestions;
    }

	public String onEdit() {
        return null;
    }

	public boolean isCreateDialogVisible() {
        return createDialogVisible;
    }

	public void setCreateDialogVisible(boolean createDialogVisible) {
        this.createDialogVisible = createDialogVisible;
    }

	public String displayList() {
        createDialogVisible = false;
        findAllVisitas();
        return "visita";
    }

	public String displayCreateDialog() {
        visita = new Visita();
        createDialogVisible = true;
        return "visita";
    }

	public String persist() {
        String message = "";
        if (visita.getCodigo() != null) {
            visitaService.updateVisita(visita);
            message = "Successfully updated";
        } else {
            visitaService.saveVisita(visita);
            message = "Successfully created";
        }
        RequestContext context = RequestContext.getCurrentInstance();
        context.execute("createDialog.hide()");
        context.execute("editDialog.hide()");
        
        FacesMessage facesMessage = new FacesMessage(message);
        FacesContext.getCurrentInstance().addMessage(null, facesMessage);
        reset();
        return findAllVisitas();
    }

	public String delete() {
        visitaService.deleteVisita(visita);
        FacesMessage facesMessage = new FacesMessage("Successfully deleted");
        FacesContext.getCurrentInstance().addMessage(null, facesMessage);
        reset();
        return findAllVisitas();
    }

	public void reset() {
        visita = null;
        createDialogVisible = false;
    }

	public void handleDialogClose(CloseEvent event) {
        reset();
    }
}
